package com.campus.controller;

import com.campus.common.CampusWall;
import com.campus.common.Result;
import com.campus.entity.FileUploads;
import com.campus.entity.UserAvatars;
import com.campus.entity.Users;
import com.campus.mapper.FileUploadsMapper;
import com.campus.utils.MD5Util;
import com.campus.utils.SnowFlakeUtil;
import com.campus.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.core.io.Resource;
import org.springframework.core.io.FileSystemResource;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class FileController {
    //文件上传路径
    @Value("${file.upload-path}")
    private String filePath;
    @Value("${file.user-avatar-upload-path}")
    private String userAvatarFilePath;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private FileUploadsMapper fileUploadsMapper;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/file/upload")
    public Result uploadFile(MultipartFile file, HttpServletRequest request) {

        //获取图片的原始名字
        String originalFilename = file.getOriginalFilename();
        long fileSize = file.getSize();
        //将图片的名字做更改防止图片名字重复
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(newFileName);
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //这里要把图片名字上传到数据库
        String token = request.getHeader(CampusWall.CAMPUS_TOKEN);
        token = tokenUtils.getToken(token);
        Users user = tokenUtils.getCurrentUser(token);
        // 使用请求中的服务器信息而不是硬编码
        String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        String avatarUrl = serverUrl + "/api/file/" + newFileName;
        FileUploads fileUpload = new FileUploads(SnowFlakeUtil.getId().toString(), user.getUserId(), originalFilename, newFileName,
                filePath, avatarUrl, fileSize, originalFilename.substring(originalFilename.lastIndexOf(".") + 1),
                file.getContentType(), MD5Util.hmacSign(newFileName), "POST", null, 1, null);
        int i = fileUploadsMapper.insertFile(fileUpload);
        if (i >= 1) {
            try {
                //写图片
                file.transferTo(new File(filePath, newFileName));


            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return Result.ok("上传成功", fileUpload);
        }
        return Result.err(Result.CODE_500, "文件上传失败");


    }

    /**
     * 用户头像上传
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/user/avatar/upload")
    public Result uploadUserAvatarFile(@RequestParam("avatar") MultipartFile file, HttpServletRequest request) {

        // 参数验证
        if (file == null || file.isEmpty()) {
            return Result.err(Result.CODE_400, "请选择要上传的头像文件");
        }

        //获取图片的原始名字
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.trim().isEmpty()) {
            return Result.err(Result.CODE_400, "文件名无效");
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.err(Result.CODE_400, "只支持图片格式文件");
        }

        long fileSize = file.getSize();
        // 验证文件大小 (2MB)
        if (fileSize > 2 * 1024 * 1024) {
            return Result.err(Result.CODE_400, "头像文件大小不能超过2MB");
        }
        //将图片的名字做更改防止图片名字重复
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        File file1 = new File(userAvatarFilePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //这里要把图片名字上传到数据库
        String token = request.getHeader(CampusWall.CAMPUS_TOKEN);
        token = tokenUtils.getToken(token);
        Users user = tokenUtils.getCurrentUser(token);
        //先删除掉本地的文件
        UserAvatars userAvatar = fileUploadsMapper.getUserAvatarByUserId(user.getUserId());
        if(userAvatar!=null){
            File avatarFile = new File(userAvatarFilePath + "\\" + userAvatar.getAvatarName());
            if (avatarFile.exists()) {
                avatarFile.delete();
            }
        }

        //这里先在数据库中删除掉头像
        fileUploadsMapper.deleteUserAvatarFile(user.getUserId());

        // 计算完整的访问路径 - 使用请求中的服务器信息而不是硬编码
        String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        String avatarUrl = serverUrl + "/api/user/avatar/" + newFileName;

        UserAvatars userAvatars = new UserAvatars(SnowFlakeUtil.getId().toString(),
                user.getUserId(), avatarUrl, file.getContentType(),
                newFileName, fileSize, originalFilename.substring(originalFilename.lastIndexOf(".") + 1)
                , 1, null, null);
        int i = fileUploadsMapper.insertUserAvatarFile(userAvatars);
        if (i >= 1) {
            try {
                //写图片到用户头像目录
                file.transferTo(new File(userAvatarFilePath, newFileName));

                // 返回包含完整访问路径的数据（不再需要设置，因为构造函数已设置）


            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return Result.ok("上传成功", userAvatars);
        }
        return Result.err(Result.CODE_500, "文件上传失败");


    }

    /**
     * 获取用户头像文件
     *
     * @param filename 文件名
     * @return
     */
    @GetMapping("/user/avatar/{filename}")
    public ResponseEntity<Resource> getUserAvatar(@PathVariable String filename) {
        try {
            File avatarFile = new File(userAvatarFilePath, filename);
            if (avatarFile.exists()) {
                Resource resource = new FileSystemResource(avatarFile);
                return ResponseEntity.ok()
                        .header("Content-Type", "image/jpeg")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 获取上传的文件
     *
     * @param filename 文件名
     * @return
     */
    @GetMapping("/file/{filename}")
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
        try {
            File file = new File(filePath, filename);
            if (file.exists()) {
                Resource resource = new FileSystemResource(file);
                return ResponseEntity.ok()
                        .header("Content-Type", "image/jpeg")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    @DeleteMapping("/file/{filename}")
    public Result deleteFile(@PathVariable String filename) {
        File uploadFile = new File(filePath + "\\" + filename);
        if (uploadFile.exists()) {
            uploadFile.delete();
            fileUploadsMapper.deleteFileByFileName(filename);
            return Result.ok("删除成功");
        }
        return Result.err(Result.CODE_500,"图片不存在");
    }
}